﻿(function ($) {
    $.fn.horizontalSplitContainer = function (option) {
        return this.each(function () {
            var container = $(this);
            var settings = $.extend({}, option);
            var helper = new $.horizontalSplitContainerHelper(container, settings);
            helper.valid();
            container.layout(function () { helper.layout() });
            container.layout();
            container.helper("horizontalSplitContainer", helper);
        });
    }

    $.horizontalSplitContainerHelper = function (_container, setting) {
        this.container = _container;
        this.valid = function () {
            if (this.container.children("[ratio='*']").size() > 1) {
                throw new Error("自动比例的item只能有1个");
            }
        };
        this.layout = function () {
            var outerwidth = 0;
            this.container.children().each(function () {
                var item = $(this);
                outerwidth += item.outerWidth() - item.width();
            });

            this.container.children("[ratio='*']").hide();
            var realwidth = this.container.width();
            var usedwidth = 0;
            this.container.children("[ratio]").each(function () {
                var item = $(this);
                var ratio = item.attr("ratio");
                if (ratio.substr(0, 1) == "#") {
                    var width = Math.round(ratio.substring(1) * 1);
                    item.width(width);
                    usedwidth += width;
                } else if (!isNaN(ratio)) {
                    var width = Math.round(realwidth * ratio / 100);
                    item.width(width);
                    usedwidth += width;
                }
            });

            var width = realwidth - outerwidth - usedwidth;
            this.container.children("[ratio='*']").width(width).show();
        };
    }
})(jQuery);